<template>
  <div ref="container" class="formula-preview"></div>
  <p v-if="errorMessage" class="formula-preview__error">{{ errorMessage }}</p>
</template>

<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref, watch } from "vue";

const props = defineProps<{
  value: string;
}>();

const container = ref<HTMLElement | null>(null);
const errorMessage = ref<string>("");
let katexInstance: typeof import("katex") | null = null;

async function ensureKatexLoaded() {
  if (!katexInstance) {
    const mod = await import("katex");
    katexInstance = mod.default ?? (mod as unknown as typeof import("katex"));
  }
  return katexInstance;
}

async function renderFormula(value: string) {
  const el = container.value;
  if (!el) return;

  const latex = value.trim();
  if (!latex) {
    el.innerHTML = "";
    errorMessage.value = "";
    return;
  }

  try {
    const katex = await ensureKatexLoaded();
    el.innerHTML = "";
    katex.render(latex, el, {
      throwOnError: false,
      displayMode: true,
      errorColor: "#d93025",
      strict: "ignore",
    });
    errorMessage.value = "";
  } catch {
    errorMessage.value = "公式解析失败，请检查语法";
  }
}

onMounted(() => {
  renderFormula(props.value);
});

watch(
  () => props.value,
  (val) => {
    renderFormula(val);
  }
);

onBeforeUnmount(() => {
  const el = container.value;
  if (el) {
    el.innerHTML = "";
  }
});
</script>

<style scoped>
.formula-preview {
  font-size: 18px;
  line-height: 1.6;
}

.formula-preview__error {
  margin-top: 8px;
  font-size: 13px;
  color: #d93025;
}
</style>
